package com.xsy.carRental.service.serviceImpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xsy.carRental.constant.MessageConstant;
import com.xsy.carRental.dto.MaintenanceAddDTO;
import com.xsy.carRental.dto.MaintenanceQueryDTO;
import com.xsy.carRental.entity.Maintenance;
import com.xsy.carRental.entity.Vehicle;
import com.xsy.carRental.mapper.MaintenanceMapper;
import com.xsy.carRental.mapper.VehicleMapper;
import com.xsy.carRental.result.PageResult;
import com.xsy.carRental.service.MaintenanceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MaintenanceServiceImpl implements MaintenanceService {
    @Autowired
    private MaintenanceMapper maintenanceMapper;
    @Autowired
    private VehicleMapper vehicleMapper;

    /**
     * 创建维修单
     *
     * @param maintenanceAddDTO
     */
    public void add(MaintenanceAddDTO maintenanceAddDTO) {
        Maintenance maintenance = new Maintenance();
        BeanUtils.copyProperties(maintenanceAddDTO, maintenance);
        maintenance.setCreatedAt(LocalDateTime.now());
        maintenanceMapper.add(maintenance);
        Vehicle vehicle = new Vehicle();
        vehicle.setVehicleId(maintenance.getVehicleId());
        vehicle.setStatus(MessageConstant.VEHICLESTATUS_MAINTENANCE);
        vehicleMapper.update(vehicle);
    }


    /**
     * 分页查询维修订单
     *
     * @param maintenanceQueryDTO
     * @return
     */
    public PageResult SearchQuery(MaintenanceQueryDTO maintenanceQueryDTO) {
        PageHelper.startPage(maintenanceQueryDTO.getPage(), maintenanceQueryDTO.getPageSize());
        Page<Maintenance> page = maintenanceMapper.SearchQuery(maintenanceQueryDTO);

        long total = page.getTotal();
        List<Maintenance> rentals = page.getResult();
        return new PageResult(total, rentals);
    }

    /**
     * 根据维修单id删除维修单
     *
     * @param maintenanceId 这个是车辆的id，根据车辆去删除对应的维修单
     */
    public void delete(Integer maintenanceId, Integer vehicleId) {
        Vehicle vehicle = new Vehicle();
        vehicle.setVehicleId(vehicleId);
        vehicle.setStatus(MessageConstant.VEHICLESTATUS_AVAILABLE);
        vehicleMapper.update(vehicle);
        maintenanceMapper.delete(maintenanceId);
    }
}
